package com.njupt.LinkTable;

/**
 * @Author: wujiaming
 * @CreateTime: 2025/2/18 15:06
 * @Description: 2. 两数相加
 * @Version: 1.0
 */


public class AddTwoNumbers_2 {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode curA = l1;
        ListNode curB = l2;
        ListNode head = new ListNode(-1);
        ListNode p = head;
        int before = 0;
        int next = 0;
        int rear = 0;
        while (curA != null && curB != null) {
            int re = curA.val + curB.val + before ;
            if (re >= 10) {
                rear = re % 10;
                next = re / 10;
            } else {
                rear = re;
                next = 0;
            }
            ListNode node = new ListNode(rear);
            p.next = node;
            p = node;
            curA = curA.next;
            curB = curB.next;
            before = next;
        }

        while(curA != null){
            int re = curA.val + before;
            if(re >= 10){
                rear = re % 10;
                next = re / 10;
            }else {
                rear = re;
                next = 0;
            }
            ListNode node = new ListNode(rear);
            p.next = node;
            p = node;
            curA = curA.next;
            before = next;
        }

        while(curB != null){
            int re = curB.val + before;
            if(re >= 10){
                rear = re % 10;
                next = re / 10;
            }else {
                rear = re;
                next = 0;
            }
            ListNode node = new ListNode(rear);
            p.next = node;
            p = node;
            curB = curB.next;
            before = next;
        }

        if (before != 0) {
            ListNode node = new ListNode(before);
            p.next = node;
            p = node;
        }
        return head.next;
    }

    public static void main(String[] args) {
        ListNode head1 = new ListNode(9);
        ListNode node1 = new ListNode(9);
        ListNode node2 = new ListNode(9);
        ListNode node3 = new ListNode(9);
        ListNode node4 = new ListNode(9);
        ListNode node5 = new ListNode(9);
        ListNode node6 = new ListNode(9);

        ListNode head2 = new ListNode(9);
        ListNode node7 = new ListNode(9);
        ListNode node8 = new ListNode(9);
        ListNode node9 = new ListNode(9);
        head1.next = node1;
        node1.next = node2; node2.next = node3; node3.next = node4; node4.next = node5; node5.next = node6;

        head2.next = node7;
        node7.next = node8; node8.next = node9;

        AddTwoNumbers_2 test = new AddTwoNumbers_2();
        ListNode listNode = test.addTwoNumbers(head1, head2);
        ListNode p = listNode;
        while (p != null) {
            System.out.print(p.val + " ");
            p = p.next;
        }


    }
}
